var http = require("https");
var cf = require("../utils/config");
/*
*
* 发送http请求
* @Param opt    json     由具体services组装好的请求信息
* @Param cb     function 回调函数
* @Param data   json     请求体
* @Param ex     json     额外参数
*    ex 说明 {
*        dataType: "json" 将结果转换成json格式(默认)，"string"不进行数据转换直接返回string结果。注意是小写字母。
*    }
* */
function parseJson(str){
  try{
    return JSON.parse(str)
  }catch(e){
    return {code:500,message:"数据转换失败"}
  }
}
exports.httpReq = function(opt,cb,data,ex){
  var x = ex||{};
  x.method = opt.method.toLowerCase();
  var reqstart = new Date();
  var req = http.request(opt,function(b){
    b.setEncoding("utf8");
    var bs = "";
    b.on("data",function(c){
        bs +=c;
    });
    b.on("end",function(){
      //console.log(bs)
      var reqdura = new Date() - reqstart;
        if(x.dataType=="string"){
          cb({body:bs,headers: b.headers,repTime:reqdura});
        }else{
          cb({body:bs,json:parseJson(bs),headers: b.headers,repTime:reqdura});
        }
    });
  });
  if(data&&(x.method=="post"|| x.method=="put")){
      if(typeof data=="object"){
        req.write(JSON.stringify(data));
      }else{
        req.write(data.toString());
      }
  }
  req.setTimeout(cf.requestWait,function(){
    req.abort();
  });
  req.on("error",function(e){
    var reqdura = new Date() - reqstart;
      console.log("++++++++++++++++++++")
      console.log(e)
    cb({body:null,error: e,headers:{},json:{code:500,message:"请求数据失败"},repTime:reqdura});
  });
  req.end();
};

/*
* 组织请求信息
* @param host   string          请求ip地址或者域名
* @param port   string|int|null 端口号，host为域名时不写
* @param method string          请求方式(get,post,put ...)默认get
* @param header json            请求头需要添加的东西,默认有content-type:application/json，可以覆盖。必须为{key:value}格式
*
* */
exports.makeOpt = function(host,port,path,method,header){
  var opt = {headers:{"content-type":"application/json"},agent:false};
  if(header)
  for(var k in header){
    opt.headers[k]=header[k];
  }
  opt.host = host;
  opt.port = port;
  opt.path = path;
  opt.method=method||"get";
  return opt;
};
exports.makeOpt1 = function(host,port,path,method,header){
    var opt = {headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Origin': '*'
        },agent:false};
    if(header)
        for(var k in header){
            opt.headers[k]=header[k];
        }
    opt.host = host;
    opt.port = port;
    opt.path = path;
    opt.method=method||"get";
    return opt;
};